package com.wtwd.campus.receiver;

import com.wtwd.campus.annotation.MsgType;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.dao.CommandRecordMapper;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.service.DeviceAppService;
import com.wtwd.campus.service.DeviceFlagService;
import com.wtwd.campus.service.DeviceInfoService;
import com.wtwd.campus.utils.ReceiverUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author mjy
 * @date 2022/12/15
 * @description
 */
@Service
@MsgType(value = Constants.APP_INSTALLATION)
public class SetAppInstallationReceiverHandler implements IReceiverHandler {


    @Resource
    private DeviceInfoService deviceInfoService;

    @Resource
    private CommandRecordMapper commandRecordMapper;

    @Resource
    private DeviceFlagService deviceFlagService;

    @Resource
    private ReceiverUtils receiverUtils;



    @Override
    public void handlerMessage(MqMessage mqMessage) {
        MqGeneralSwitchResult mqGeneralSwitchResult = (MqGeneralSwitchResult) mqMessage.getObject();
        String imei = mqGeneralSwitchResult.getImei();
        String commandNumber = mqGeneralSwitchResult.getCommandNumber();
        Integer flag = mqGeneralSwitchResult.getResult();
        //处理指令回复时间
        String date = mqGeneralSwitchResult.getDeviceDate();
        String time = mqGeneralSwitchResult.getDeviceTime();
        Long time1 = getTime(date, time);
        DeviceInfo deviceInfo = deviceInfoService.getDeviceByImei(imei);
        if (deviceInfo!=null){
            CommandRecord commandRecord = commandRecordMapper.getCommandRecordByCondition2(imei, commandNumber, Constants.APP_INSTALLATION);
            if (commandRecord != null) {//处理业务
                deviceFlagService.setAppInstallationFlag(deviceInfo.getDeviceId(),flag);
                //修改设备信息
                deviceInfo.setLastUpTime(System.currentTimeMillis());
                deviceInfoService.modifyDeviceInfo(deviceInfo);
                //删除缓存中的指令
                String delKey=Constants.APP_INSTALLATION.concat("-").concat(commandNumber);
                receiverUtils.deleteCommandInRedis(imei, delKey);
                //完善指令下发记录
                receiverUtils.completeCommandRecord(Constants.APP_INSTALLATION, imei, commandNumber, null, Constants.COMMAND_COMPLETE, time1);
            }
        }
        return;
    }
}
